<?php
/**
 * Created by PhpStorm.
 * User: Lin Hui
 * Date: 2017/6/14
 * Time: 16:32
 */

namespace controllers;

use lib\Model;

class Metal
{
    public function __construct()
    {

    }

    private $tmp = [];
    public function save()
    {
        $tmp = explode(',', $_GET['str']);
        $line = $_GET['line'];
        $total = $_GET['total'];

        $db = [
            'host'=>'127.0.0.1',
            'name'=>'metal',
            'user'=>'root',
            'pass'=>'@worrylin',
            'port'=>'3306',
            'prefix'=>'',
        ];
        if($tmp) {
            if($line % 500 == 0) {
                echo "{$line}\n";
            }
            $percent = $line / $total * 100;
            if(is_int($percent)) {
                echo $percent ."%\n";
            }

            $model = new Model($db);
            $table = strtolower($tmp[0]);
            $model->table($table);
            $add = array(
                'time'=>strtotime($tmp[1].$tmp[2]),
                'open'=>$tmp[3],
                'high'=>$tmp[4],
                'low'=>$tmp[5],
                'close'=>$tmp[6],
            );
            if($model->find($add['time'])) {
                return 3;
            }
            if(!($model->create($add) && $model->add())) {
                return 4;
            }
            return 0;
        } else {
            return 5;
        }

    }

    public function saveByFile()
    {
        //设置英国时区
        date_default_timezone_set('UTC');
        //获取文件
        $file = $_GET['file'];
        if(file_exists($file)) {
            //计时
            $start = time();
            //打开文件
            $op = fopen($file, 'r');
            $i = 0;
            //初始化表
            $model = new Model(\lib\App::$config['db_finance']);
            $table = strtolower(pathinfo($file, PATHINFO_FILENAME));
            $model->query("CREATE TABLE IF NOT EXISTS `{$table}` (
                  `time` int(10) unsigned NOT NULL COMMENT '时间',
                  `open` decimal(10,6) unsigned NOT NULL COMMENT '开盘',
                  `high` decimal(10,6) unsigned NOT NULL COMMENT '最高',
                  `low` decimal(10,6) unsigned NOT NULL COMMENT '最低',
                  `close` decimal(10,6) unsigned NOT NULL COMMENT '收盘',
                  PRIMARY KEY (`time`)
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
            $model->table($table);
//            $max = $model->query("SELECT MAX(time) as max FROM {$table}")[0]['max'];

//            fgets($op);
            //读取文件
            while(!feof($op)) {
//                if($i % 100000 == 0) {
//                    echo "Done count:{$i} time(seconds):".(time() - $start)."\n";
//                    $start = time();
//                }
                //将数据压入临时数组
                $str = fgets($op);
                $i++;
                if($tmp = explode(',', $str)) {
                    if (!isset($tmp[1])) {
                        continue;
                    }
                    $this->tmp[] = [
                        'time' => strtotime($tmp[1] . $tmp[2]),
                        'open' => $tmp[3],
                        'high' => $tmp[4],
                        'low' => $tmp[5],
                        'close' => $tmp[6],
                    ];
                }
                //设置 1000个数组一轮询
                if($i % 1000 == 0) {
                    $this->handlerData($model, $i);
                    continue;
                }
            }
            //处理剩余数据
            $this->handlerData($model, $i);
            return 0;
        } else {
            echo "file {$file} doesn't exists.\n";
            return 3;
        }
    }

    /**
     *处理数据
     */
    public function handlerData($model, &$i)
    {
        //查询数据中是否有重复的值
        $times = array_column($this->tmp, 'time');
        $repeat = $model->where('`time` IN ('.join(',', $times).')')->field('time')->select();
        //去除已有的数据
        if($repeat) {
            $repeat = array_column($repeat, 'time');
            foreach($this->tmp as $key => $item) {
                if(in_array($item['time'], $repeat)) {
                    unset($this->tmp[$key]);
                }
            }
        }
        //添加数据
        try {
            if($this->tmp) {
                $rs = $model->addAll($this->tmp);
            }
        } catch (\Exception $e) {
            echo $e->getCode();
            echo "数据添加失败";
            return 4;
        }

        //清除临时数组
        $this->tmp = [];
    }

    public function saveBySQLFile()
    {
        $file = $_GET['file'];
        if(file_exists($file)) {
            $start = time();
            $op = fopen($file, 'r');
            $i = 0;
            $table = strtolower(pathinfo($file, PATHINFO_FILENAME));

            $sqlFile = $_GET['sqlDir'].DIRECTORY_SEPARATOR.$table.'.sql';
            if(!$sqlFile) {
                echo "Sql file is empty.\n";
                return 5;
            }
            if(file_exists($sqlFile)) {
                unlink($sqlFile);
            }
            touch($sqlFile);
            file_put_contents($sqlFile, "
                CREATE TABLE IF NOT EXISTS `{$table}` (
                  `time` int(10) unsigned NOT NULL COMMENT '时间',
                  `open` decimal(10,6) unsigned NOT NULL COMMENT '开盘',
                  `high` decimal(10,6) unsigned NOT NULL COMMENT '最高',
                  `low` decimal(10,6) unsigned NOT NULL COMMENT '最低',
                  `close` decimal(10,6) unsigned NOT NULL COMMENT '收盘',
                  PRIMARY KEY (`time`)
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8;\n", FILE_APPEND);
			fgets($op);
            while(!feof($op)) {
                
                /*if($i % 100000 == 0) {
                    echo "Done count:{$i} time(seconds):".(time() - $start)."\n";
                    $start = time();
                }*/
                $str = fgets($op);
                if($str && $tmp = explode(',', $str)) {
					$i++;
                    file_put_contents($sqlFile, "INSERT INTO {$table} (`time`,`open`,`high`,`low`,`close`) VALUE (".strtotime($tmp[1].$tmp[2]).", {$tmp[3]}, {$tmp[4]}, {$tmp[5]}, {$tmp[6]});\n", FILE_APPEND);
                }
            }
			echo "Success:$i.\n";
			//echo "Done count:{$i} time(seconds):".(time() - $start)."\n";
            return 0;
        } else {
            echo "file {$file} doesn't exists.\n";
            return 3;
        }
    }
}
